package com.example.mystore.servlets.ctrl;

import com.example.mystore.entity.Commodity;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class CartButtonServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String toDo = req.getServletPath();
        if(toDo.equals("/toClear")){
            req.getSession().removeAttribute("cart");
        }else {
            int commID = Integer.parseInt(req.getParameter("id"));

            Commodity getCommodity = null;
            //        从ServletContext获得商品信息
            HashMap<String, ArrayList<Commodity>> commodityHM =
                    (HashMap<String, ArrayList<Commodity>>) getServletContext().getAttribute("commodityHM");
            for (ArrayList<Commodity> commodityArrayList : commodityHM.values()) {
                for (Commodity commodity : commodityArrayList){
                    if (commID == commodity.getId()){
                        getCommodity = commodity;
                        break;
                    }
                }
            }
            //        从Session中获得购物车的HashMap对象，没有就新建一个
            HashMap<Commodity,Integer> cart = (HashMap<Commodity, Integer>) req.getSession().getAttribute("cart");
            if(cart == null){
                cart = new HashMap<Commodity,Integer>();
            }
            switch (toDo){
                case "/toDel":cart.remove(getCommodity);break;
                case "/toAdd":
                    Integer count = cart.put(getCommodity,1);
                    if(count != null){
                        cart.put(getCommodity,count+1);
                    }break;
                case "/toReduce":
                    int count1 = cart.get(getCommodity);
                    if(count1 > 1){
                    cart.put(getCommodity,count1-1);
                    }
            }
            //        获得新数据后购物车覆盖原先的购物车Session
            req.getSession().setAttribute("cart",cart);
        }

//        重定向到购物车页面
        resp.sendRedirect(req.getContextPath()+"/Cart.jsp");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     doGet(req,resp);
    }
}
